package org.xiaoyu.feign.core;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperServiceOne {

	public static ZooKeeper zk;
	
	public static String rootPath = "/test";

	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
	      //创建ZooKeeper实例
        zk = new ZooKeeper("172.16.40.130:2181", 100, new Wa());
        
        String path = "/test";
        Stat stat = zk.exists(path, new Wa());
        if(stat == null) {
            zk.create(path, "ROOT".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        String servicePath = path + "/service1";
        
       Thread one =  new Thread(new runOne("service1"));
       one.start();
       zk.close();
 
	}
	
	
	static class runOne implements Runnable{

		
		private String serviceName;
		
		public runOne(String serviceName) {
			this.serviceName = serviceName;
		}
		
		@Override
		public void run() {
			 String servicePath = rootPath + "/" + serviceName;
        	try {
				List<String> ips = zk.getChildren(servicePath, new Watcher() {						
					@Override
					public void process(WatchedEvent event) {
						System.out.println(event.getPath());
						System.out.println(event.getType());
						System.out.println(event.getState());
						try {
							List<String> ips = zk.getChildren(servicePath, this);
							for (String ip : ips) {
								System.out.println(ip);
							}
						} catch (KeeperException | InterruptedException e) {						
							e.printStackTrace();
						}
					}
				});
	            for (String ip : ips) {
	            	System.out.println(ip);
	    		}
			} catch (KeeperException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	static class Wa implements Watcher{
		@Override
		public void process(WatchedEvent event) {
			System.out.println(event.getPath());
			System.out.println(event.getType());
			System.out.println(event.getState());
			
		}
	}
}
